/*
 * @Author       : lg
 * @Date         : 2022-06-24 22:48:08
 * @LastEditors  : lg
 * @LastEditTime : 2022-06-24 22:57:39
 * @FilePath     : \TwoWeeksFaceTest\ws-server\server\ws.p2p.js
 * @description  :
 */
// 获得服务的类
const { WebSocketServer } = require("ws");
// 创建实例
const wsServer = new WebSocketServer({ port: 3000 });
// 保存多个窗口client的ws连接
const list = {};
// 监听连接事件
wsServer.on("connection", curWs => {
  // 连接成功
  console.info("connected",list);
  curWs.on("message", msg => {
    const rawData = JSON.parse(msg.toString());
    if(list[rawData.event] !== curWs){
      list[rawData.event] && list[rawData.event].close();
      list[rawData.event] = curWs;
    }
    console.info("ws server received message", rawData);

    rawData.data = Number(rawData.data) + 1;
    rawData.msg = "更新成功！";
    rawData.code = 200;

    list[rawData.event].send(JSON.stringify(rawData));
  });
});
